package com.mfl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mfl.common.PageResult;
import com.mfl.constant.IdentityConstant;
import com.mfl.constant.MessageConstant;
import com.mfl.context.BaseContext;
import com.mfl.exception.PostAlreadyExistsException;
import com.mfl.mapper.AdminMapper;
import com.mfl.mapper.PostMapper;
import com.mfl.mapper.PostRemarkMapper;
import com.mfl.mapper.UserMapper;
import com.mfl.pojo.dto.PostDTO;
import com.mfl.pojo.dto.PostPageQueryDTO;
import com.mfl.pojo.entity.Admin;
import com.mfl.pojo.entity.Post;
import com.mfl.pojo.entity.User;
import com.mfl.pojo.vo.PostPageQueryVO;
import com.mfl.pojo.vo.PostVO;
import com.mfl.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class PostServiceImpl implements PostService {

    @Autowired
    private PostMapper postMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PostRemarkMapper postRemarkMapper;

    /**
     * 分页查询帖子
     *
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(PostPageQueryDTO pageQueryDTO) {
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        Page<PostPageQueryVO> page = postMapper.pageQuery(pageQueryDTO);
        page.getResult().forEach(item -> {
            if (item.getIdentity() == IdentityConstant.ADMINISTRATOR) {
                Admin admin = adminMapper.getByAdminId(item.getCreateUser());
                item.setUserName(admin.getName());
            } else if (item.getIdentity() == IdentityConstant.ORDINARY_USER) {
                User user = userMapper.getById(item.getCreateUser());
                item.setUserName(user.getName());
            }
        });
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增帖子
     *
     * @param postDTO
     */
    @Override
    public void insert(PostDTO postDTO) {
        // 判断帖子是否存在
        Post p = postMapper.selectByPostTitle(postDTO.getPostTitle());
        if (p != null) {
            throw new PostAlreadyExistsException(MessageConstant.POST_ALREADY_EXISTS);
        }

        Post post = Post.builder()
                .postTitle(postDTO.getPostTitle())
                .content(postDTO.getContent())
                .identity(postDTO.getIdentity().equals("admin") ? IdentityConstant.ADMINISTRATOR : IdentityConstant.ORDINARY_USER)
                .createUser(BaseContext.getCurrentId())
                .createTime(LocalDateTime.now())
                .build();
        postMapper.insert(post);
    }

    /**
     * 批量删除帖子
     *
     * @param ids
     */
    @Transactional
    @Override
    public void batchDelete(List<Integer> ids) {
        postMapper.deleteByIds(ids);
        // 删除对应的帖子回复
        postRemarkMapper.deleteByPostIds(ids);
    }

    /**
     * 根据id查询帖子
     *
     * @param id
     * @return
     */
    @Override
    public PostVO getPostById(int id) {
        Post post = postMapper.getPostById(id);
        PostVO vo = PostVO.builder()
                .id(post.getId())
                .postTitle(post.getPostTitle())
                .content(post.getContent())
                .createTime(post.getCreateTime())
                .build();
        if (post.getIdentity() == IdentityConstant.ADMINISTRATOR) {
            Admin admin = adminMapper.getByAdminId(post.getCreateUser());
            vo.setUserName("管理员");
        } else if (post.getIdentity() == IdentityConstant.ORDINARY_USER) {
            User user = userMapper.getById(post.getCreateUser());
            vo.setUserName(user.getName());
            vo.setAvatar(user.getAvatar());
        }
        return vo;
    }

    /**
     * 修改帖子
     *
     * @param postDTO
     */
    @Override
    public void update(PostDTO postDTO) {
        Post post = Post.builder()
                .id(postDTO.getId())
                .postTitle(postDTO.getPostTitle())
                .content(postDTO.getContent())
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        postMapper.update(post);
    }

    /**
     * 查询最新帖子
     *
     * @return
     */
    @Override
    public PageResult queryLatelyPost(PostPageQueryDTO postPageQueryDTO) {
        PageHelper.startPage(postPageQueryDTO.getPage(), postPageQueryDTO.getPageSize());
        Page<PostPageQueryVO> page = postMapper.pageQueryLately(postPageQueryDTO);
        page.getResult().forEach(item -> {
            if (item.getIdentity() == IdentityConstant.ADMINISTRATOR) {
                Admin admin = adminMapper.getByAdminId(item.getCreateUser());
                item.setUserName("管理员");
            } else if (item.getIdentity() == IdentityConstant.ORDINARY_USER) {
                User user = userMapper.getById(item.getCreateUser());
                item.setUserName(user.getName());
                item.setAvatar(user.getAvatar());
            }
            // 查询帖子数量
            int postNum = postRemarkMapper.getPostNum(item.getId());
            item.setPostNum(postNum);
        });
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 查询三天前的帖子
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult queryThreeDaysAgoPost(PostPageQueryDTO pageQueryDTO) {
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        Page<PostPageQueryVO> page = postMapper.queryThreeDaysAgoPost(pageQueryDTO);
        page.getResult().forEach(item -> {
            if (item.getIdentity() == IdentityConstant.ADMINISTRATOR) {
                Admin admin = adminMapper.getByAdminId(item.getCreateUser());
                item.setUserName("管理员");
            } else if (item.getIdentity() == IdentityConstant.ORDINARY_USER) {
                User user = userMapper.getById(item.getCreateUser());
                item.setUserName(user.getName());
                item.setAvatar(user.getAvatar());
            }
            // 查询帖子数量
            int postNum = postRemarkMapper.getPostNum(item.getId());
            item.setPostNum(postNum);
        });
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 根据用户id查询帖子
     * @param id
     * @return
     */
    @Override
    public PageResult pageQueryUserPost(PostPageQueryDTO postPageQueryDTO) {
        PageHelper.startPage(postPageQueryDTO.getPage(), postPageQueryDTO.getPageSize());
        Page<PostPageQueryVO> page = postMapper.pageQueryUserPost(postPageQueryDTO);
        // 查询用户信息
        User user = userMapper.getById(postPageQueryDTO.getUserId());
        page.getResult().forEach(item -> {
            item.setAvatar(user.getAvatar());
            item.setUserName(user.getName());
            // 查询帖子数量
            int postNum = postRemarkMapper.getPostNum(item.getId());
            item.setPostNum(postNum);
        });
        return new PageResult(page.getTotal(), page.getResult());
    }
}
